#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MULTICAST_GROUP "224.0.0.1"
#define PORT 5556
#define SERVICE_INFO "MyService is available!"

int main() {
    int sockfd;
    struct sockaddr_in group_addr;
    char message[1024];

    // 创建 UDP 套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置组播地址
    memset(&group_addr, 0, sizeof(group_addr));
    group_addr.sin_family = AF_INET;
    group_addr.sin_addr.s_addr = inet_addr(MULTICAST_GROUP);
    group_addr.sin_port = htons(PORT);

    // 准备要发送的服务信息
    strcpy(message, SERVICE_INFO);

    while (1) {
        // 发送服务信息
        if (sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&group_addr, sizeof(group_addr)) < 0) {
            perror("sendto failed");
        }
        printf("Sent service info: %s\n", message);
        sleep(5); // 每 5 秒发送一次服务信息
    }

    // 关闭套接字
    close(sockfd);
    return 0;
}